<template>
    <Row type="flex" justify="center" style="margin-top: 150px;" @keyup.enter="handleSubmit">
        <Col>
            <Form ref="form" :model="form" :rules="rules">
                <FormItem prop="username">
                    <Input prefix="md-person" placeholder="环信用户名" v-model="form.username"/>
                </FormItem>
                <FormItem prop="pwd">
                    <Input type="password" prefix="md-lock" placeholder="环信密码" v-model="form.pwd"/>
                </FormItem>
                <FormItem>
                    <Button type="primary" style="width:100%;" @click="handleSubmit">登录</Button>
                </FormItem>
                <FormItem style="text-align: center">
                    <a target="_blank" href="https://webim-h5.easemob.com/#/register">注册</a>
                </FormItem>
            </Form>
        </Col>
    </Row>
</template>

<script>
    export default {
        name: 'Login',
        data() {
            return {
                form: {
                    username: '',
                    pwd: '',
                    isShowTip: false
                },
                rules: {
                    username: [
                        {required: true, message: '用户名不能为空', trigger: 'blur'}
                    ],
                    pwd: [
                        {required: true, message: '密码不能为空', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            handleSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        let vm = this;
                        this.$im.conn.open({
                            apiUrl: this.$im.config.apiURL,
                            appKey: this.$im.config.appkey,
                            user: this.form.username,
                            pwd: this.form.pwd,
                            success: function (message) {
                                vm.$util.setWebImUsername(message.user.username);
                                vm.$util.setWebImNickName(message.user.nickname);
                                vm.$util.setWebImToken(message.access_token);
                                vm.$router.push({
                                    name: 'home'
                                })
                            },
                            error: function () {
                                // 环信的重试机制会触发多次error
                                if (!this.isShowTip) {
                                    this.isShowTip = true;
                                    vm.$Message.error({content: '登录环信失败'})
                                }
                            }
                        });
                    }
                });
            }
        }
    }
</script>

<style scoped>
    body {
        text-align: center;
    }
</style>
